import * as vscode from 'vscode';
import * as fs from 'fs'
import * as nls from 'vscode-nls';
import * as path from 'path';

const localize = nls.config({ messageFormat: nls.MessageFormat.file })();

export class ProjectProvider implements vscode.WebviewViewProvider {
    static VIEW_ID = 'smart-project-manager'
    private context: vscode.ExtensionContext
    public projects: ProjectCache[] = []
    public webview?: vscode.WebviewView
    constructor(context: vscode.ExtensionContext) {
        this.context = context
    }
    static register(context: vscode.ExtensionContext) {
        const provider = new ProjectProvider(context)
        const disposable = vscode.window.registerWebviewViewProvider(this.VIEW_ID, provider)

        return {
            disposable,
            provider
        }
    }
    resolveWebviewView(webviewView: vscode.WebviewView, context: vscode.WebviewViewResolveContext, token: vscode.CancellationToken): Thenable<void> | void {
        webviewView.webview.options = {
            enableScripts: true
        };
        this.webview = webviewView;
        const message = {
            openFolder: localize('view.open.folder', 'Open Folder'),
        }
        webviewView.webview.html = this.getHtml(webviewView.webview, message);

        webviewView.webview.onDidReceiveMessage(e => {
            console.log('后台', e.type)
            switch (e.type) {
                case 'getProjects':
                    webviewView.webview.postMessage({
                        type: 'setProjects',
                        data: this.projects
                    })
                    break
                case 'openFolder':
                    this.openFolder(e.data)
                    break
                case 'removeFolder':
                    this.removeFolder(e.data)
                    break
            }
        })
    }

    static syncProjects(provider: ProjectProvider) {
        const folders = vscode.workspace.workspaceFolders;

        const ar: ProjectCache[] = []
        const cache: ProjectCache[] | undefined = provider.context.globalState.get('projects');
        if (cache) {

            for (let i = 0; i < cache.length; i++) {
                const ok = fs.existsSync(cache[i].path);
                if (ok) {
                    cache[i].opening = false
                    ar.push(cache[i])
                }
            }
        }

        if (folders) {
            for (let i = 0; i < folders.length; i++) {
                const index = ar.findIndex(a => a.path === folders[i].uri.fsPath);
                if (index === -1) {
                    ar.push({
                        name: folders[i].name,
                        path: folders[i].uri.fsPath,
                        time: Date.now(),
                        opening: true,
                    })
                } else {
                    ar[index].opening = true
                }
            }
        }

        const temp = ar.sort((a, b) => b.time - a.time)
        provider.context.globalState.update('projects', temp)
        provider.projects = temp
    }

    private openFolder(url: string) {
        if (!url) {
            vscode.commands.executeCommand('vscode.openFolder', undefined, /* forceNewWindow */ false);
            return
        }
        const index = this.projects.findIndex(p => p.path == url);
        if (index > -1) {
            this.projects[index].time = Date.now();
            this.context.globalState.update('projects', this.projects)
        }
        const uri = vscode.Uri.file(url);
        vscode.commands.executeCommand('vscode.openFolder', uri, /* forceNewWindow */ false);
    }

    private removeFolder(url: string) {
        const index = this.projects.findIndex(a => a.path === url);
        if (index == -1) {
            return
        }
        this.projects.splice(index, 1);
        this.context.globalState.update('projects', this.projects);
    }

    private getHtml(webview: vscode.Webview, message: { [k: string]: string }) {
        const cssUrl = webview.asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri, 'assets/project.css'))
        const jsUrl = webview.asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri, 'assets/project.js'))
        return `
        <!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>sg-script</title>
    <style>
      *{
        margin: 0;
        padding: 0;
      }
      .loading{
        width: 100%;
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 32px;
        color: #fff;
        background-color: black;
      }
    </style>
    <link rel="stylesheet" href="${cssUrl}" />
  </head>
  <body oncontextmenu="return false">
    <div id="app" dropzone>
    <div class="loading">
        loading
      </div>
    </div>
    <script>
        const message = ${JSON.stringify(message)}
      document.addEventListener("contextmenu", (event) => {
      event.preventDefault();
})
    </script>
    <script src="${jsUrl}"></script>
  </body>
</html>
        `
    }
}